package com.yk.satoken.demos.minio.controller;

import com.yk.satoken.demos.base.response.ActionResult;
import com.yk.satoken.demos.minio.service.FileService;
import com.yk.satoken.demos.minio.util.OptimizeUtil;
import com.yk.satoken.demos.minio.util.UpUtil;
import com.yk.satoken.demos.minio.vo.UploaderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author YangKai
 * @create 2024-06-02 15:40
 * @version: 1.0
 * @Description:
 */

@Slf4j
@RestController
@RequestMapping("/api/file")
public class UtilsController {

    @Value("${config.AllowUploadFileType:}")
    private String allowUploadFileType;

    @Autowired
    private FileService fileService;

    /**
     * 上传文件/图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/uploader", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ActionResult<UploaderVO> uploader(MultipartFile file) {
        String fileType = UpUtil.getFileType(file);
        // 验证类型
        if (!OptimizeUtil.fileType(allowUploadFileType, fileType)) {
            return ActionResult.fail("");
        }
        UploaderVO vo = fileService.uploaderVO(file);
        return ActionResult.success(vo);
    }


    /**
     * @param path 文件的路径
     */
    @GetMapping("/download")
    public void downloadByPath(String path) {
        fileService.downloadFileByPath(path);
    }

    @GetMapping("/getObjectUrl")
    public String getObjectUrl() {
        return fileService.getObjectUrl();
    }
}
